﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SubtitleDownloader.Providers
{
	public class Subtitles : ISubtitleProvider
	{
		public string Name
		{
			get { return "Subtitles"; }
		}

		public IEnumerable<SubtitleItem> GetSubtitles(VideoItem videoItem)
		{
			var seriesPage = Utils.GetHtml(
				new Uri(String.Format("http://www.subtitle.co.il/browse.php?speechval=&q={0}&qs=true", FixSeriesName(videoItem.Name))));
			if (seriesPage != null) {
				var seasons = Regex.Matches(seriesPage, @"<a[^>]+?seasonlink_(?<link>\d+?)\""[^>]+?>(?<season>\d+?)</",
					RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
				var fixedSeasonNumber = seasons.Count - videoItem.Season;
				if (fixedSeasonNumber >= 0) {
					var seasonPage = Utils.GetHtml(new Uri(
						String.Format("http://www.subtitle.co.il/getajax.php?seasonid={0}", seasons[fixedSeasonNumber].Groups["link"].Value)));
					if (seasonPage != null) {
						var episodes = Regex.Matches(seriesPage, @"<a[^>]+?episodelink_(?<link>\d+?)\""[^>]+?>(?<episode>\d+?)</",
							RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
						var fixedEpisodeNumber = episodes.Count - videoItem.Episode;
						if (fixedEpisodeNumber >= 0) {
							var episodePage = Utils.GetHtml(new Uri(
								String.Format("http://www.subtitle.co.il/getajax.php?episodedetails={0}", episodes[fixedEpisodeNumber].Groups["link"].Value)));
							var subtitles = Regex.Matches(episodePage,
								"<[^>]+?subtitle_tab\">.*?<[^>]+?subt_download\">.*?<[^>]+?href=\"(?<link>.*?)\"[^>]+?>.*?<[^>]+?subtitle_title\"[^>]+?>(?<title>.*?)</",
								RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
							foreach (Match subtitle in subtitles) {
								yield return new SubtitleItem(subtitle.Groups["title"].Value,
									new Uri(new Uri("http://www.subtitle.co.il/"), subtitle.Groups["link"].Value));
							}
						}
					}
				}
			}
		}

		private string FixSeriesName(string seriesName)
		{
			if (seriesName == null)
				return seriesName;
			var textInfo = new System.Globalization.CultureInfo("en-US").TextInfo;
			return textInfo.ToTitleCase(seriesName.Replace(' ', '+'));
		}
	}
}
